<template>
    <el-popover placement="bottom-start" :width="200" trigger="click" v-model:visible="visible">
        <div class="icon-selector">
            <el-input v-model="searchQuery" placeholder="选择图标 ..." clearable>
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
            <div class="icons-list">
                <div v-for="(icon, index) in filteredIcons" :key="index" @click="selectIcon(icon)" class="icon-item"
                    :class="{ 'selected': selectedIcon === icon }">
                    <i :class="['iconfont', 'icon-'+icon]"></i>
                </div>
            </div>
        </div>
        <template #reference>
            <el-button v-if="selectedIcon" circle>
                <i :class="['iconfont', selectedIcon]" style="margin-left: 6px;"></i>
            </el-button>
            <el-button v-else circle>+</el-button>
        </template>
    </el-popover>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 假设你已经有了一个获取Iconfont.json的方法
import iconsData from '@/assets/iconfont/iconfont.json';

const visible = ref(false);
const searchQuery = ref('');
const selectedIcon = ref(null);

// 从JSON文件中提取图标名称列表
const iconsList = computed(() => iconsData.glyphs.map(glyph => glyph.font_class));

// 根据搜索框内容过滤图标
const filteredIcons = computed(() =>
    iconsList.value.filter(icon =>
        icon.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
);

function selectIcon(icon) {
    selectedIcon.value = 'icon-'+icon;
    visible.value = false;
    emit('update:modelValue', 'icon-' + icon); // 如果使用v-model绑定
}

// 定义emit事件，用于父组件监听选择变化
const emit = defineEmits(['update:modelValue']);

onMounted(() => {
    // 可能需要做一些初始化操作
});
</script>

<style scoped>
.icon-selector {
    display: flex;
    flex-direction: column;
}

.icons-list {
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow-y: auto;
}

.icon-item {
    padding: 4px;
    cursor: pointer;
}

.icon-item:hover,
.icon-item.selected {
    background-color: #e6f7ff;
}

.icon-item i {
    font-size: 24px;
}
</style>